package struct.intermediate.queue;

/**
 * @author MAX
 * @version 1.0
 * @description 中级数据结构-动态数组循环队列，解决动态数组队列出站时间复杂度O(n)的问题
 * @date 2022/1/13 11:30
 */
public class ArrayLoopQueue<E> implements Queue<E> {

    private E[] data;
    private int front, tail;

    public ArrayLoopQueue() {
        this(10);
    }

    public ArrayLoopQueue(int capacity) {
        data = (E[])new Object[capacity];
        front = tail = 0;
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == front) {
            resize(data.length * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
    }

    @Override
    public E dequeue() {
        if(isEmpty()) throw new RuntimeException("Queue Empty");

        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;

        if(size() <= data.length / 3) resize(data.length / 2);
        return ret;
    }

    @Override
    public E getFront() {
        return data[front];
    }

    @Override
    public int size() {
        return tail >= front ? tail - front : tail - front + data.length;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    private void resize(int capacity) {
        E[] newData = (E[])new Object[capacity];
        int sz = size();
        for(int i = 0 ; i < sz ; i ++)
            newData[i] = data[(i + front) % data.length];

        data = newData;
        front = 0;
        tail = sz;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("front[");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            res.append(data[i]);
            if((i + 1) % data.length != tail) res.append(",");
        }

        res.append("]tail");
        return res.toString();
    }
}
